/*
 * Modified sample code from mgwt showcase
 * Copyright 2010 Daniel Kurka
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
package de.dhbw.vs.permachat.client.activities.login;

import java.util.logging.Logger;

import com.google.gwt.core.client.Scheduler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.ui.AcceptsOneWidget;
import com.google.web.bindery.event.shared.EventBus;
import com.googlecode.mgwt.dom.client.event.tap.TapEvent;
import com.googlecode.mgwt.dom.client.event.tap.TapHandler;
import com.googlecode.mgwt.mvp.client.MGWTAbstractActivity;
import com.googlecode.mgwt.ui.client.dialog.Dialogs;

import de.dhbw.vs.permachat.client.ClientFactory;
import de.dhbw.vs.permachat.client.UserInformation;

/**
 * @author flo
 * 
 */
public class LoginActivity extends MGWTAbstractActivity {
	private static final Logger LOGGER = Logger.getLogger(LoginActivity.class.toString());

	private final ClientFactory clientFactory;
	private LoginView view;

	public LoginActivity(ClientFactory clientFactory) {
		this.clientFactory = clientFactory;

	}

	@Override
	public void start(AcceptsOneWidget panel, final EventBus eventBus) {
		view = clientFactory.getLoginView();
		
		view.setTitle("GeoChat");

		addHandlerRegistration(view.getLoginButton().addTapHandler(
				new TapHandler() {

					@Override
					public void onTap(TapEvent event) {
						processLogin();

					}
				}));
		
		addHandlerRegistration(view.getUserNameFieldSender().addKeyUpHandler(new KeyUpHandler() {
			
			@Override
			public void onKeyUp(KeyUpEvent event) {
				if(KeyCodes.KEY_ENTER == event.getNativeKeyCode()){
					processLogin();
				}
			}
		}));

		panel.setWidget(view);
		
		Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand () {
	        public void execute () {
	            view.focusUserNameField();
	        }
	    });
	}

	protected void processLogin() {
		String userName = view.getUserNameField().getText();
		if(userName != null && userName.length() > 0){
			LOGGER.info("Logged in user " + userName);
			UserInformation.getUser().setName(userName);
			
			this.clientFactory.getEventBus().fireEvent(new LoggedInEvent());
		} else{
			Dialogs.alert("Wrong Input", "Name must not be empty.", null);
		}
	}
}
